<?php

namespace App\Http\Controllers\Admin;

use App\power;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Exception;

class AdminController extends Controller {

    /*
    *	构造函数
    */
    function __construct(){
        date_default_timezone_set('PRC');
        $this->admin = DB::table('admin');
        $path = app_path();
        $this->planPath =$path."/Http/Controllers/Admin/";
    }

    /*
    *	添加管理员界面
    */
    public function add(Request $request){
        $input = $request->input();

        unset($input['repasswd']);

        if(!empty($input['id'])){
            if(!empty($input['pwd'])){
                $input['pwd'] = password_hash($input['pwd'], PASSWORD_BCRYPT);
            }else{
                unset($input['pwd']);
            }
            $this->admin->where("id","=",$input['id'])->update($input);
        }else {
            if(!$input['account'] || !$input['pwd'])return self::fail('账号或密码为空!');
            $da = $this->admin->where('account',"=",$input['account'])->first();
            if(isset($da->id)) return self::fail('账号已存在！');

            $input['pwd'] = password_hash($input['pwd'], PASSWORD_BCRYPT);
            $input['add_time'] = time();
            $this->admin->insert($input);
        }

        return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '修改成功！'
        ]);

    }

    /*
    *	编辑管理员界面
    */
    public function edit(Request $request,$id){
        $res = $this->admin->where('id',"=",$id)->first();
        $list = DB::table('admin_role')->orderBy('role_id','desc')->get();
        return 	view('admin/admin_edit',['list'=>$list,'res'=>$res,'id'=>$id]);
    }

    /**
     *  添加管理员界面
     */
    public function admin_add(){
        $list = DB::table('admin_role')->orderBy('role_id','desc')->get();
        return 	view('admin/admin_add',['list'=>$list]);
    }

    /*
    *	管理员列表
    */
    public function li(){
        $list = $this->admin->join('admin_role','admin_role.role_id','=','admin.role_id')->paginate(15);

        return view('admin/admin_li',['list'=>$list]);
    }

    /*
    *	删除管理员
    */
    public function del(Request $request,$id){
        if(empty($id)) return self::fail('參數有誤!');
        $da=$this->admin->where("id","=",$id)->first();
        if(!isset($da->id)) return self::fail('賬號有誤!');
        if($da->id==1) return self::fail('超級管理員不能刪除!');
        $this->admin->where("id","=",$id)->delete();
        return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '删除成功！'
        ]);
    }

    /*
    *	禁用管理员
    */
    public function ban(Request $request,$id){
        if(!$id) return self::fail('參數有誤!');
        $da=$this->admin->where('id',"=",$id)->first();
        if(!$da->id) return self::fail('賬號有誤!');
        $act_list = DB::table('admin_role')->where('role_id','=',$da->role_id)->first();
        if($act_list->act_list=='all') return self::fail('超級管理員不能修改!');
        if($da->status==1){
            $res=$this->admin->where('id',"=",$id)->update(["status"=>0]);
        }else{
            $res=$this->admin->where('id',"=",$id)->update(["status"=>1]);
        }
        return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '操作成功！'
        ]);
    }

    //权限列表
    public function right_list(Request $request){
        $input = $request->input();
        $where = [];
        $name = '';
        if (!empty($input['name'])) {
            $name = $input['name'];
            $where[] = ['name','like',"%{$input['name']}%"];
        }

        //权限组
        $right_list = DB::table('system_menu')->where($where)->paginate(15);
        $system_menu_count = DB::table('system_menu')->where($where)->count();
        return view('admin/admin_right_list',['right_list'=>$right_list,'system_menu_count'=>$system_menu_count,'name'=>$name]);
    }

    //添加权限模板
    public function admin_add_right(){
        $info = [];

        $planList = array();
        $dirRes   = opendir($this->planPath);
        while($dir = readdir($dirRes))
        {
            if(!in_array($dir,array('.','..','.svn')))
            {
                $planList[] = basename($dir,'.php');
            }
        }

        return view('admin/admin_add_right',['data'=>$info,'planList'=>$planList]);
    }

    //编辑权限模板
    public function admin_edit_right(Request $request,$id){
        if($id){
            $info = DB::table('system_menu')->where('id','=',$id)->first();
            $info->right = explode(',', $info->right);
        }

        $planList = array();
        $dirRes   = opendir($this->planPath);
        while($dir = readdir($dirRes))
        {
            if(!in_array($dir,array('.','..','.svn')))
            {
                $planList[] = basename($dir,'.php');
            }
        }

        return view('admin/admin_edit_right',['data'=>$info,'planList'=>$planList,'id'=>$id]);
    }


    //编辑权限
    public function edit_right_do(Request $request){
        $data = $request->input();
        $data['right'] = implode(',',$data['right']);
        if(!empty($data['id'])){
            DB::table('system_menu')->where('id','=',$data['id'])->update($data);
        }else{
            if(DB::table('system_menu')->where('name','=',$data['name'])->count()>0)throw new Exception("该权限名称已添加，请检查");
            unset($data['id']);
            DB::table('system_menu')->insert($data);
        }

        return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '删除成功！'
        ]);
    }

    //删除权限
    public function right_del(Request $request,$id){
        if(!empty($id)){
            DB::table('system_menu')->where('id','=',$id)->delete();
        }else{
            return self::fail('參數有誤!');
        }

        return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '删除成功！'
        ]);
    }

    //控制器获取下面的function
    function ajax_get_action(Request $request)
    {
        $input = $request->input();
        $control = $input['controller'];

        $advContrl = get_class_methods('App\Http\Controllers\Admin\\'.str_replace('.php','',$control));
        $baseContrl = get_class_methods('App\Http\Controllers\Controller');
        $baseContrl[] = '__construct';

        $diffArray  = array_diff($advContrl,$baseContrl);

        $html = '';
        foreach ($diffArray as $val){
            $html .= "<option value='".$val."'>".$val."</option>";
        }
        exit($html);
    }

    //角色管理
    public function role(){
        $list = DB::table('admin_role')->orderBy('role_id','desc')->paginate(10);
        $admin_role_count = DB::table('admin_role')->count();
        return view('admin/admin_role',['list'=>$list,'admin_role_count'=>$admin_role_count]);
    }

    //添加角色
    public function add_role(){
        $modules = [];
        $right = DB::table('system_menu')->orderBy('id','asc')->get();
        foreach ($right as $val){
            $modules[$val->group][] = $val;
        }
        return view('admin/admin_role_add',['modules'=>$modules]);
    }

    //角色详情
    public function role_info(Request $request,$id){
        $role_id =$id;
        $detail = array();
        $modules= [];
        $detail = DB::table('admin_role')->where("role_id",'=',$role_id)->first();
        $detail->act_list = explode(',', $detail->act_list);

        $right = DB::table('system_menu')->orderBy('id','asc')->get();
        foreach ($right as $val){
            if(!empty($detail)){
                $val->enable = in_array($val->id, $detail->act_list);
            }
            $modules[$val->group][] = $val;
        }

        return view('admin/admin_role_info',['detail'=>$detail,'modules'=>$modules,'id'=>$id]);
    }


    //角色保存
    public function roleSave(Request $request){
        $data = $request->input();
        $res = $data['data'];
        if(!isset($data['right'])){
            $data['right']='';
        }
        $res['act_list'] = is_array($data['right']) ? implode(',', $data['right']) : '';

        if(empty($res['role_id'])){
            $r = DB::table('admin_role')->insertGetId($res);
            $data['role_id']=$r;
        }else{
            $r =DB::table('admin_role')->where('role_id','=',$res['role_id'])->update($res);
        }

        return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '操作成功！'
        ]);
    }


    //删除角色
    public function roleDel(Request $request,$id){
        $where[] = ['role_id','=',$id];
        $admin = $this->admin->where($where)->first();
        if(isset($admin->id))return self::fail('請先清空所屬該角色的管理員!');

        DB::table('admin_role')->where("role_id",'=',$id)->delete();

        return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '操作成功！'
        ]);
    }

    public function power()
    {

        $request_all = \request()->input();

        $where = [];

        if(!empty($request_all['start_time']) && !empty($request_all['end_time'])){
            $where[] = ['created_at', '>=', $request_all['start_time']];
            $where[] = ['created_at', '<=', $request_all['end_time']];
        }

        $data = (new power())->where($where)->orderBy('id','desc')->paginate(10);

        $result = [
            'data' => $data,
            'end_time' => $request_all['end_time']??'',
            'start_time' => $request_all['start_time']??'',
        ];

        return view('admin/admin_power', $result);

    }

    public function powerDelete(Request $request, $id)
    {
        $model = power::find($id);

        if (!$model) {
            return self::fail('可能因为某些原因删除失败，请稍后再试!');
        }

        $model->delete();
        return self::success();
    }

    public function powerDeleteAll(Request $request)
    {

        $ids = $request->ids;

        $ids_array = explode(',',$ids);

        return DB::table('power')->whereIn('id', $ids_array)->delete();

    }

    public function powerInfo($id)
    {
        $model = power::find($id);
        if (!$model) {
            return self::fail('可能因为某些原因删除失败，请稍后再试！');
        }
        return view('admin/admin_power_info',['data' => $model]);
    }
}
